{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Supervised Learning Algorithms: Lasso Regression"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*In this template, only **data input** and **input/target variables** need to be specified (see \"Data Input & Variables\" section for further instructions). None of the other sections needs to be adjusted. As a data input example, .csv file from IBM Box web repository is used.*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Libraries"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Run to import the required libraries.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib notebook\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.preprocessing import MinMaxScaler\n",
    "from sklearn.model_selection import train_test_split"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Data Input and Variables"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Define the data input as well as the input (X) and target (y) variables and run the code. Do not change the data & variable names **['df', 'X', 'y']** as they are used in further sections.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Data Input\n",
    "# df = \n",
    "\n",
    "### Defining Variables  \n",
    "# X = \n",
    "# y = \n",
    "\n",
    "### Data Input Example \n",
    "df = pd.read_csv('https://ibm.box.com/shared/static/q6iiqb1pd7wo8r3q28jvgsrprzezjqk3.csv')\n",
    "\n",
    "X = df[['horsepower']]\n",
    "y = df['price']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. The Model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Run to build the model.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "lasso regression linear model intercept: 3984.172831038173\n",
      "lasso regression linear model coeff:[33549.01456544]\n",
      "\n",
      "Non-zero features: 1\n",
      "\n",
      "R-squared score (training): 0.623\n",
      "R-squared score (test): 0.666\n",
      "\n",
      "Features with non-zero weight (sorted by absolute magnitude):\n",
      "\thorsepower, 33549.015\n"
     ]
    }
   ],
   "source": [
    "from sklearn.linear_model import Lasso\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0)\n",
    "scaler = MinMaxScaler()\n",
    "\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "linlasso = Lasso(alpha=2.0, max_iter = 10000).fit(X_train_scaled, y_train)\n",
    "\n",
    "### Intercept & coefficient, # of non-zero features & weights, R-squared for training & test data set\n",
    "print('lasso regression linear model intercept: {}'\n",
    "     .format(linlasso.intercept_))\n",
    "print('lasso regression linear model coeff:{}'\n",
    "     .format(linlasso.coef_))\n",
    "print('\\nNon-zero features: {}'\n",
    "     .format(np.sum(linlasso.coef_ != 0)))\n",
    "print('\\nR-squared score (training): {:.3f}'\n",
    "     .format(linlasso.score(X_train_scaled, y_train)))\n",
    "print('R-squared score (test): {:.3f}\\n'\n",
    "     .format(linlasso.score(X_test_scaled, y_test)))\n",
    "print('Features with non-zero weight (sorted by absolute magnitude):')\n",
    "\n",
    "for e in sorted (list(zip(list(X), linlasso.coef_)),\n",
    "                key = lambda e: -abs(e[1])):\n",
    "    if e[1] != 0:\n",
    "        print('\\t{}, {:.3f}'.format(e[0], e[1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.1. Regularization parameter alpha on R-squared"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Run to check how alpha affects the model score.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Lasso regression: effect of alpha regularization\n",
      "parameter on number of features kept in final model\n",
      "\n",
      "Alpha = 0.50\n",
      "Features kept: 1, r-squared training: 0.62, r-squared test: 0.67\n",
      "\n",
      "Alpha = 1.00\n",
      "Features kept: 1, r-squared training: 0.62, r-squared test: 0.67\n",
      "\n",
      "Alpha = 2.00\n",
      "Features kept: 1, r-squared training: 0.62, r-squared test: 0.67\n",
      "\n",
      "Alpha = 3.00\n",
      "Features kept: 1, r-squared training: 0.62, r-squared test: 0.67\n",
      "\n",
      "Alpha = 5.00\n",
      "Features kept: 1, r-squared training: 0.62, r-squared test: 0.66\n",
      "\n",
      "Alpha = 10.00\n",
      "Features kept: 1, r-squared training: 0.62, r-squared test: 0.66\n",
      "\n",
      "Alpha = 20.00\n",
      "Features kept: 1, r-squared training: 0.62, r-squared test: 0.66\n",
      "\n",
      "Alpha = 50.00\n",
      "Features kept: 1, r-squared training: 0.62, r-squared test: 0.65\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print('Lasso regression: effect of alpha regularization\\n\\\n",
    "parameter on number of features kept in final model\\n')\n",
    "\n",
    "for alpha in [0.5, 1, 2, 3, 5, 10, 20, 50]:\n",
    "    linlasso = Lasso(alpha, max_iter = 10000).fit(X_train_scaled, y_train)\n",
    "    r2_train = linlasso.score(X_train_scaled, y_train)\n",
    "    r2_test = linlasso.score(X_test_scaled, y_test)\n",
    "    \n",
    "    print('Alpha = {:.2f}\\nFeatures kept: {}, r-squared training: {:.2f}, \\\n",
    "r-squared test: {:.2f}\\n'\n",
    "         .format(alpha, np.sum(linlasso.coef_ != 0), r2_train, r2_test))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
